package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.result.Result;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //1.准备日期列表数据
        List<LocalDate> dateList=getDataList(begin, end);

        //2.准备营业额列表数据
        List<Double> turnoverList = new ArrayList();

            //营业额=订单状态为已完成的订单金额
            //查询order表，条件：状态-已完成，下单时间
        dateList.forEach(date -> {
                //查询当天的营业额
            Map map=new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("begin", LocalDateTime.of(date, LocalTime.MIN));    //将LocalDate转成LocalDateTime对象，当天的00:00:00
            map.put("end", LocalDateTime.of(date, LocalTime.MAX));      //将LocalDate转成LocalDateTime对象，当天的23:59:59

                //调用mapper，查询数据
            Double turnover = ordersMapper.sumByMap(map);
            //如果当天的营业额为空，则设置为0.0
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        });

        //3构造TurnoverReportVO对象，并返回
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))   //将数组转成字符串，用逗号分隔
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //1.获取日期列表
        List<LocalDate> dataList = getDataList(begin, end);


            //循环遍历日期列表，获取每个日期的注册用户数
        List<Integer> newUserList = new ArrayList<>();  //新用户集合
        List<Integer> totalUserList = new ArrayList<>();//总用户集合
        dataList.forEach(date -> {
            //2.获取新增用户数据
            Map map = new HashMap();
            map.put("begin", LocalDateTime.of(date, LocalTime.MIN));
            map.put("end", LocalDateTime.of(date, LocalTime.MAX));
                //调用mapper，查询数据
            Integer newUsers = userMapper.countUserByMap(map);
            newUserList.add(newUsers);


            map.put("begin",null);
            //3.调用mapper 获取总用户数据
            Integer TotalUsers = userMapper.countUserByMap(map);
            totalUserList.add(TotalUsers);
        });

        //4.构造UserReportVO对象并返回
        return UserReportVO.builder()
                .dateList(StringUtils.join(dataList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        //1.获取日期列表
        List<LocalDate> dataList = getDataList(begin, end);

        List<Integer> OrdercountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();

        Integer totalOrderCount = 0;
        Integer validOrderCount = 0;

            //循环遍历列表
        for (LocalDate date : dataList) {

            //2.获取每日总订单列表数
                Map map = new HashMap();
                map.put("beginTime",LocalDateTime.of(date,LocalTime.MIN));
                map.put("endTime",LocalDateTime.of(date,LocalTime.MAX));
                Integer totalOrder= ordersMapper.countByMap(map);

                OrdercountList.add(totalOrder);

            //3.获取每日成功订单列表数
                map.put("status",Orders.COMPLETED);
                Integer validOrder= ordersMapper.countByMap(map);

                validOrderCountList.add(validOrder);

            //4.获取订单总数
                totalOrderCount +=totalOrder;

            //5.获取成功订单总数
                validOrderCount +=validOrder;
        }

        //6.计算完成率
        double orderCompletionRate = 0.0;
        if (totalOrderCount != 0){
            orderCompletionRate = (validOrderCount+0.0) / totalOrderCount;
        }

        //7.封装数据并返回
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dataList,","))
                .orderCountList(StringUtils.join(OrdercountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 销量top10数据统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        //1.构造 nameList
        List<String> nameList =new ArrayList();

        //2.构造 numberList
        List<Integer>  numberList =new ArrayList();

        //查询订单表跟订单明细表，条件：下单时间，订单状态为已完成
        Map map = new HashMap();
        map.put("status",Orders.COMPLETED);
        map.put("beginTime",LocalDateTime.of(begin, LocalTime.MIN));
        map.put("endTime",LocalDateTime.of(end, LocalTime.MAX));

        List<GoodsSalesDTO> list= ordersMapper.sumTop10(map);
        //循环遍历。将数据加入到集合中
        for (GoodsSalesDTO dto : list) {
            nameList.add(dto.getName());
            numberList.add(dto.getNumber());
        }

        //3.封装SalesTop10ReportVO并返回
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }

    /**
     * 导出营业数据
     */
    @Override
    public void exportBusinessData(HttpServletResponse response)  {
        //1.查询数据库，获取营业数据--查询最近20天的运营数据
        LocalDate begin = LocalDate.now().minusMonths(1);      //当前时间的一个月前
        LocalDate end = LocalDate.now().minusDays(1);        //当前时间

            //查询概要数据
        BusinessDataVO data = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN),
                                                                LocalDateTime.of(end, LocalTime.MAX));

        try {
            //2.通过poi将数据写入到excel文件中
            InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

            //基于模板文件创建一个新的excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);
            //获取表格文件的Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间：" + begin + "至" + end);
            //获得第4行，并填充数据
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(data.getTurnover());
            row.getCell(4).setCellValue(data.getOrderCompletionRate());
            row.getCell(6).setCellValue(data.getNewUsers());

            //获得第5行，并填充数据
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(data.getValidOrderCount());
            row.getCell(4).setCellValue(data.getUnitPrice());


            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate localDate = begin.plusDays(i);
                BusinessDataVO dataVO = workspaceService.getBusinessData(LocalDateTime.of(localDate, LocalTime.MIN),
                                                                         LocalDateTime.of(localDate, LocalTime.MAX));

                row= sheet.getRow(i+7);
                row.getCell(1).setCellValue(localDate.toString());
                row.getCell(2).setCellValue(dataVO.getTurnover());
                row.getCell(3).setCellValue(dataVO.getValidOrderCount());
                row.getCell(4).setCellValue(dataVO.getOrderCompletionRate());
                row.getCell(5).setCellValue(dataVO.getUnitPrice());
                row.getCell(6).setCellValue(dataVO.getNewUsers());

            }

            //3.通过输出流将excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 获取指定日期范围内的日期列表
     * @param begin
     * @param end
     * @return
     */
    private  List<LocalDate> getDataList(LocalDate begin, LocalDate end){
        List<LocalDate> dateList = new ArrayList<>();
        //循环插入日期数据
        while ( !begin.isAfter(end)){
            //注意：小心死循环
            dateList.add(begin);
            begin=begin.plusDays(1);
        }
        log.info("dataList={}",dateList);
        return dateList;
    }
}
